package com.lantosec.hmrp.modules.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.modules.category.entity.*;
import com.lantosec.hmrp.modules.category.mapper.AssetsInfoMapper;
import com.lantosec.hmrp.modules.category.service.IAssetsCategoryService;
import com.lantosec.hmrp.modules.category.service.IAssetsDirectoryService;
import com.lantosec.hmrp.modules.category.service.IAssetsImageService;
import com.lantosec.hmrp.modules.category.service.IAssetsInfoService;
import com.lantosec.hmrp.modules.category.vo.AssetsInfoVO;
import com.lantosec.hmrp.modules.system.entity.SysParameter;
import com.lantosec.hmrp.modules.system.service.ISysAreaService;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.system.service.ISysParameterService;
import com.lantosec.hmrp.modules.system.service.ISysUserService;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 资产信息表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-03-31
 */
@Service
@Primary
@Log4j2
@SuppressWarnings("all")
public class AssetsInfoServiceImpl extends ServiceImpl<AssetsInfoMapper, AssetsInfo> implements IAssetsInfoService {

    @Autowired
    private ISysUploadsService uploadsService;

    @Autowired
    private ISysParameterService parameterService;

    @Autowired
    private IAssetsCategoryService assetsCategoryService;

    @Autowired
    private ISysAreaService areaService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IAssetsDirectoryService directoryService;

    @Autowired
    private IAssetsImageService imageService;

    @Override
    public Page<AssetsInfo> queryPage(PageVO<AssetsInfo> page, AssetsInfoVO condition,Integer permissionsType) {
        String deptId = TokenUtil.getDeptId();
        if(null == condition.getIsPrint()){
            condition.setIsPrint(3);
        }
        if(null == permissionsType){
            permissionsType = 1;
        }
        PageVO<AssetsInfo> param = baseMapper.selectPage(page, new QueryWrapper<AssetsInfo>()
                .eq(StringUtils.isNotEmpty(condition.getCategoryId()), "category_id", condition.getCategoryId()) //资产类别
                .eq(StringUtils.isNotEmpty(condition.getUseDeptId()), "use_dept_id", condition.getUseDeptId())  //使用部门
                .eq(StringUtils.isNotEmpty(condition.getAreaId()), "area_id", condition.getAreaId())        //所在区域
                .eq(null != condition.getLableType(),"lable_type",condition.getLableType())
                .eq(StringUtils.isNotEmpty(condition.getAssetsState()), "assets_state", condition.getAssetsState()) //资产状态
                .like(StringUtils.isNotEmpty(condition.getAssetsName()),"assets_name",condition.getAssetsName())    //资产名称
                .eq(permissionsType == 2,"use_dept_id",deptId)
                .isNotNull(0 == condition.getIsPrint(),"print_time")
                .isNull(1 == condition.getIsPrint(),"print_time")
                .eq("review_state",1)
                .orderByDesc("create_time"));
        List<AssetsInfo> records = param.getRecords();
        records.forEach(it->{
            String photoList = it.getPhotoList();
            if (StringUtils.isNotEmpty(photoList)) {
                List list = uploadsService.pictureUrl(photoList);
                it.setPictureUrl(list);
            }
            String categoryId = it.getCategoryId();
            if(StringUtils.isNotEmpty(categoryId)){
                String categoryName = assetsCategoryService.getById(categoryId).getCategoryName();
                it.setCategoryName(categoryName);
            }
        });
        return page.setRecords(param.getRecords());
    }

    @Override
    public Page<AssetsInfo> unCheckPage(PageVO<AssetsInfo> page, AssetsInfoVO condition) {
        String deptId = TokenUtil.getDeptId();
        PageVO<AssetsInfo> param = baseMapper.selectPage(page, new QueryWrapper<AssetsInfo>()
                .eq("review_state", 0)
                .like(StringUtils.isNotEmpty(condition.getAssetsName()),"assets_name",condition.getAssetsName())
                .orderByDesc("create_time"));
        List<AssetsInfo> records = param.getRecords();
        records.forEach(it->{
            String photoList = it.getPhotoList();
            if (StringUtils.isNotEmpty(photoList)) {
                List list = uploadsService.pictureUrl(photoList);
                it.setPictureUrl(list);
            }
            String categoryId = it.getCategoryId();
            if(StringUtils.isNotEmpty(categoryId)){
                String categoryName = assetsCategoryService.getById(categoryId).getCategoryName();
                it.setCategoryName(categoryName);
            }
        });
        return page.setRecords(param.getRecords());
    }

    @Override
    public void delete(List assetsIds) {
        assetsIds.forEach(it->{
            baseMapper.realDelete((String)it);
        });
    }

    @Override
    public void audit(List assetsIds) {
        assetsIds.forEach(it->{
            baseMapper.audit((String)it);
            //审核通过把固定资产插入到目录表
            AssetsInfo info = baseMapper.selectOne(new QueryWrapper<AssetsInfo>()
                    .eq("assets_id", it));
            if(StringUtils.isEmpty(info.getDirId())){
                AssetsDirectory assetsDirectory = new AssetsDirectory();
                BeanUtils.copyProperties(info, assetsDirectory);
                String dirId = baseMapper.selectMaxDirId();
                if(StringUtils.isEmpty(dirId)){
                    dirId = "LT0001";
                }
                assetsDirectory.setDirId(dirId);
                assetsDirectory.setManualFlag(1);
                directoryService.save(assetsDirectory);
                //更新目录表的时候把dirId更新资产信息表
                baseMapper.updateDirId((String)it,dirId);
            }
            //固定资产存在目录表时更新类别信息
            if(!info.getDirId().startsWith("LT")){
                String categoryId = info.getCategoryId();
                baseMapper.updateCategoryId(info.getDirId(),categoryId);
            }
        });
    }

    @Override
    public void create(AssetsInfo entity) {
        //获取固定资产编码
        String assetsCode = getAssetsCode();
        entity.setAssetsCode(assetsCode);
        entity.setCreateTime(new Date());
        queryName(entity);
        if(StringUtils.isEmpty(entity.getSpecification())){
            entity.setSpecification("");
        }
        if(StringUtils.isEmpty(entity.getBrand())){
            entity.setBrand("");
        }
        baseMapper.insert(entity);
        //保存图片至资产图片上传记录表
        if(StringUtils.isNotEmpty(entity.getPhotoList())){
            saveImage(entity.getPhotoList(),entity.getAssetsId());
        }
    }

    private AssetsInfo queryName(AssetsInfo entity) {
        //所在区域
        if(StringUtils.isNotEmpty(entity.getAreaId())){
            String areaName = areaService.getById(entity.getAreaId()).getAreaName();
            entity.setAreaName(areaName);
        }
        //使用人
        if(StringUtils.isNotEmpty(entity.getUseUserId())){
            String username = userService.getById(entity.getUseUserId()).getName();
            entity.setUseUser(username);
        }
        //使用部门
        if(StringUtils.isNotEmpty(entity.getUseDeptId())){
            String deptName = deptService.getById(entity.getUseDeptId()).getDeptName();
            entity.setUseDept(deptName);
        }
        //归属部门
        if(StringUtils.isNotEmpty(entity.getBelongDeptId())){
            String deptName = deptService.getById(entity.getBelongDeptId()).getDeptName();
            entity.setBelognDept(deptName);
        }
        //管理员
        if(StringUtils.isNotEmpty(entity.getManageUserId())){
            String username = userService.getById(entity.getManageUserId()).getName();
            entity.setManageUser(username);
        }
        //资产类别
        if(StringUtils.isNotEmpty(entity.getCategoryId())){
            String categoryName = assetsCategoryService.getById(entity.getCategoryId()).getCategoryName();
            entity.setCategoryName(categoryName);
        }
        return entity;
    }

    public String getAssetsCode() {
        String dictionariesName = parameterService.getOne(new QueryWrapper<SysParameter>()
                .eq("para_name","fourHospital")).getParaValue();
        //查询最大的固定资产编码加1
        String id = baseMapper.selectMaxAssetsCode();
        if(StringUtils.isEmpty(id)){
            id = "000001";
        }
        return dictionariesName + id;
    }

    public void saveImage(String photoList, String assetsId) {
        List<String> strings = Arrays.asList(photoList.split(","));
        for (String s : strings) {
            AssetsImage image = new AssetsImage();
            image.setAssetsId(assetsId);
            image.setUploadId(s);
            image.setSubmitTime(new Date());
            image.setSubmitUser("管理员");
            image.setSubmitUserId("superuser");
            imageService.save(image);
        }
    }

    @Override
    public void updateInfo(AssetsInfo entity) {
        AssetsInfo assetsInfo = queryName(entity);
        baseMapper.updateById(entity);
        //保存图片至资产图片上传记录表
        if(StringUtils.isNotEmpty(entity.getPhotoList())){
            saveImage(entity.getPhotoList(),entity.getAssetsId());
        }
    }

    @Override
    public AssetsInfo getInfoByAssetsId(String assetsId) {
        AssetsInfo info = baseMapper.selectOne(new QueryWrapper<AssetsInfo>()
                .eq(String.valueOf(AssetsInfo.ColName.assets_id), assetsId));
        if(StringUtils.isNotEmpty(info.getPhotoList())){
            List list = uploadsService.pictureUrl(info.getPhotoList());
            info.setPictureUrl(list);
        }
        return info;
    }

    @Override
    public AssetsInfo getAssetsInfoByCode(String assetsCode) {
        AssetsInfo info = baseMapper.selectOne(new QueryWrapper<AssetsInfo>()
                .eq(String.valueOf(AssetsInfo.ColName.assets_code), assetsCode));
        if(StringUtils.isNotEmpty(info.getPhotoList())){
            List list = uploadsService.pictureUrl(info.getPhotoList());
            info.setPictureUrl(list);
        }
        return info;
    }

    @Override
    public AssetsCount getCountForLableType(String deptId, String areaId,String categoryList){
        AssetsCount param = baseMapper.getCountForLableType(deptId,areaId,categoryList);
        return param;
    }

    @Override
    public AssetsCount getCheckCount(String planId ,String deptId, String areaId,String categoryList) {
        AssetsCount param = baseMapper.getCheckCount(planId,deptId,areaId,categoryList);
        return param;
    }

    @Override
    public List<AssetsInfo> getAssetsLableList(String deptId, String areaId,String categoryList) {
        return baseMapper.getAssetsLableList(deptId,areaId,categoryList);
    }

    @Override
    public List<AssetsInfo> getCountByRfid(String deptId, String areaId, String categoryList) {
        return baseMapper.getCountByRfid(deptId,areaId,categoryList);
    }

    @Override
    public List<Statistical> statisticalByUserDept() {
        return baseMapper.statisticalByUserDept();
    }

    @Override
    public List<Statistical> statisticalBycategoryId() {
        return baseMapper.statisticalBycategoryId();
    }

    @Override
    public List<Statistical> statisticalByLableType() {
        return baseMapper.statisticalByLableType();
    }

    @Override
    public List<Statistical> statisticalByState() {
        return baseMapper.statisticalByState();
    }

    @Override
    public List<Statistical> statisticalByPrice() {
        List<Statistical> statisticals = baseMapper.statisticalByPrice();
        statisticals.forEach(it->{
            if (StringUtils.isEmpty(it.getNowPrice())) {
                it.setNowPrice("0");
            }
            if(StringUtils.isEmpty(it.getPrice())){
                it.setPrice("0");
            }
        });
        return statisticals;
    }
}
